from django.core.signals import request_finished, request_started, got_request_exception
from django.dispatch import receiver

from .utils.out import get_context_manager


@receiver(request_started)
def context_start(sender, **kwargs):
    """
        当请求开始时，创建上下文
    """
    get_context_manager()  # 创建上下文


@receiver(request_finished)
def context_end(sender, **kwargs):
    """
        当请求正常结束时，清理上下文
    """
    get_context_manager().clear()  # 清理上下文


@receiver(got_request_exception)
def context_exception(sender, **kwargs):
    """
        当请求异常结束时，清理上下文
    """
    get_context_manager().clear()  # 清理上下文